package main

import (
	"errors"
	"fmt"
)

//Queue 队列
type Queue struct {
	//队列元素
	elements []interface{}
	//队首索引
	front int
	//队尾索引
	rear int
}

//NewQueue 初始化队列
func NewQueue(cap int) *Queue {
	if cap <= 0 {
		cap = 8
	}
	queue := &Queue{
		front:    0,
		rear:     0,
		elements: make([]interface{}, cap),
	}
	return queue
}

//Enqueue 入队
func (q *Queue) Enqueue(data interface{}) error {
	if (q.rear+1)%len(q.elements) == q.front {
		return errors.New("队列已满")
	}
	q.elements[q.rear] = data
	q.rear = (q.rear + 1) % len(q.elements)
	return nil
}

//Dequeue 出队
func (q *Queue) Dequeue() (interface{}, error) {
	if q.rear == q.front {
		return nil, errors.New("队列已空")
	}
	outData := q.elements[q.front]
	q.front = (q.front + 1) % len(q.elements)
	return outData, nil
}

func (q *Queue) Output() {
	for i := q.front; i != q.rear; i = (i + 1) % len(q.elements) {
		fmt.Println(q.elements[i])
	}
}

//IsEmpty 是否空队列
func (q *Queue) IsEmpty() bool {
	return q.rear == q.front
}
